/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.shrikanthravi.customnavigationdrawer2.utils;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;

import java.util.ArrayList;
import java.util.Optional;

/**
 * FractionChangeManager
 *
 * @author wangyin
 * @since 2021/06/23
 */
public class FractionChangeManager {
    /**
     * FractionManager
     */
    private final FractionManager mFragmentManager;

    /**
     * mContainerViewId
     */
    private final int mContainerViewId;

    /**
     * mFragments
     */
    private final ArrayList<Fraction> mFragments;

    /**
     * 构造函数
     *
     * @param fm FractionManager
     * @param containerViewId containerViewId
     * @param fragments fragments
     */
    public FractionChangeManager(FractionManager fm, int containerViewId, ArrayList<Fraction> fragments) {
        this.mFragmentManager = fm;
        this.mContainerViewId = containerViewId;
        this.mFragments = fragments;
        initFragments();
    }

    private void initFragments() {
        for (int i = 0; i < mFragments.size(); i++) {
            Optional<Fraction> fractionByTag = mFragmentManager.getFractionByTag(String.valueOf(i));
            if (fractionByTag.isPresent()) {
                mFragmentManager.startFractionScheduler().hide(mFragments.get(i)).submit();
            } else {
                mFragmentManager.startFractionScheduler()
                        .add(mContainerViewId, mFragments.get(i), String.valueOf(i))
                        .hide(mFragments.get(i)).submit();
            }
        }
        setFragments(0);
    }

    /**
     * 界面切换控制
     *
     * @param index 当前的fragment
     */
    public void setFragments(int index) {
        for (int i = 0; i < mFragments.size(); i++) {
            FractionScheduler ft = mFragmentManager.startFractionScheduler();
            Fraction fragment = mFragments.get(i);
            if (i == index) {
                ft.show(fragment).submit();
            } else {
                ft.hide(fragment).submit();
            }
        }
    }
}